package com.example.learningnote.bank;

import android.util.Log;

public class Bank {
	private String account;// 账号
	private int balance;// 账户余额

	public Bank(String account, int balance) {
		this.account = account;
		this.balance = balance;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public int getBalance() {
		return balance;
	}

	public void setBalance(int balance) {
		this.balance = balance;
	}

	@Override
	public String toString() {
		return "Bank [account:" + account + ", balance:" + balance + "]";
	}

	// 存款
	// 同步锁 synchronized 确保 bank 对象的互斥访问，防止并发修改
	// 方法级别同步 synchronized
	public synchronized void saveAccount() {

		// 获取当前的账号余额
		int balance = getBalance();
		try {
			Thread.sleep(5000); // 模拟耗时
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		balance += 100;
		setBalance(balance);
		Log.d("BANK", Thread.currentThread().getName() + " saveAccount after: " + balance);
		// 存款后唤醒等待的取款线程
		// notifyAll();
		notify();//
	}

	public void drawAccount() {
		// 代码块级别同步 synchronized
		synchronized (this) {
			// 在不同的位置处添加sleep方法 模拟线程竞争的情况 比如如网络请求、数据库读写
			// 获得当前的帐户余额
			while (getBalance() < 200) { // 余额不足时等待
				try {
					Log.d("BANK", Thread.currentThread().getName() + " drawAccount waiting, balance: " + getBalance());
					wait(); // 释放锁，进入等待
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			int balance = getBalance();
			try {
				Thread.sleep(1000); // 模拟耗时
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			balance -= 200;
			setBalance(balance);
			Log.d("BANK", Thread.currentThread().getName() + " drawAccount after: " + balance);
		}
	}
}
